using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using Newtonsoft.Json;
using System.IO;

[DefaultExecutionOrder(-100)]               // 避免加载序列化文件的时候和数据加载有冲突
public class DataManager : MonoBehaviour {
    
    public static DataManager instance;     // 单例

    [Header("事件监听")]
    public VoidEventSO saveDataEvent;       // 保存游戏数据的事件监听
    public VoidEventSO loadDataEvent;       // 加载游戏数据的事件监听

    private List<ISaveAble> saveableList = new List<ISaveAble>();   // 数据列表

    private Data saveData;                  // 保存的数据
    private string jsonFolder;              // 序列化路径

    private void Awake() {
        if (instance == null) {     // 单例
            instance = this;
        } else {
            Destroy(this.gameObject);
        }

        saveData = new Data();

        // 无论任何平台，只要调用这个api就可以获取对应的序列化路径
        jsonFolder = Application.persistentDataPath + "/SAVE DATA/";

        // 读取序列化文件中的游戏数据
        ReadSavedData();
    }

    private void OnEnable() {
        saveDataEvent.OnEventRaised += Save;
        loadDataEvent.OnEventRaised += Load;
    }

    private void OnDisable() {
        saveDataEvent.OnEventRaised -= Save;
        loadDataEvent.OnEventRaised -= Load;
    }

    private void Update() {
        // if (Keyboard.current.lKey.wasPressedThisFrame) {
        //     Load();
        // }
    }

    public void RegisterSaveData(ISaveAble saveable) {
        if (!saveableList.Contains(saveable)) {
            saveableList.Add(saveable);
        }
    }

    public void UnRegisterSaveData(ISaveAble saveable) {
        saveableList.Remove(saveable);
    }

    public void Save() {
        foreach (var saveable in saveableList) {
            saveable.GetSaveData(saveData);
        }

        // 存储序列化数据的文件路径
        var resultPath = jsonFolder + "data.sav";

        // 序列化数据
        var jsonData = JsonConvert.SerializeObject(saveData);

        // 如果文件不存在，则创建字典
        if (!File.Exists(resultPath)) {
            Directory.CreateDirectory(jsonFolder);
        }

        // 写入文件
        File.WriteAllText(resultPath, jsonData);

        // 测试
        // foreach (var item in saveData.characterPosDict) {
        //     Debug.Log(item.Key + " " + item.Value);
        // }
    }

    public void Load() {
        foreach (var saveable in saveableList) {
            saveable.LoadData(saveData);
        }
    }

    /// <summary>
    ///     从文件中读取保存的数据
    /// </summary>
    private void ReadSavedData() {
        var resultPath = jsonFolder + "data.sav";

        if (File.Exists(resultPath)) {
            // 获取string形式的json数据
            var stringData = File.ReadAllText(resultPath);

            // 将string形式的json数据转换为Data对象
            var jsonData = JsonConvert.DeserializeObject<Data>(stringData);
            
            // 获取到数据
            saveData = jsonData;
        }
    }

}
